package org.example.file;

import org.junit.jupiter.api.Test;

import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;

/**
 * file:FileManipulate.class
 * function:
 *
 * @author shaodan wang
 * @date 2024-08-26
 */


public class FileManipulate  {


    /**
     * 删除文件和文件夹
     * @throws Exception
     */
    @Test
    public void test001() throws Exception {
        //遍历删除a以及a下的所有文件和文件夹
        File file = new File("D:\\temp\\a");
        Files.walkFileTree(Paths.get(file.getAbsolutePath()), new SimpleFileVisitor<Path>() {
            // 先去遍历删除文件
            @Override
            public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
                Files.delete(path);
                System.out.println("文件夹" + path.getFileName() + "被删除");
                return FileVisitResult.CONTINUE;
            }

            // 再去遍历删除目录
            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                Files.delete(dir);
                System.out.println("文件夹" + dir.getFileName() + "被删除");
                return FileVisitResult.CONTINUE;
            }
        });
    }


}
